package com.wtone.platform.gat.images.gat.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.Consts;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.conn.ConnectionKeepAliveStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: aiLin
 * @Date: 2020/8/15 16:58
 * @desc: DigestHttpClientUtil
 */
@Slf4j
public class DigestHttpClientUtil {


    /***
     * cd /home/wtone/java-service/java/java/accesscontrol
     * chmod -R 777  accesscontrol-0.0.1-SNAPSHOT.jar
     * nohup java -Xms256m -Xmx1024m -Xmn126m -XX:MaxMetaspaceSize=256m -jar accesscontrol-0.0.1-SNAPSHOT.jar  > /home/wtone/java-service/java/java/logs/accesscontrol.log &
     * tail -f ../logs/accesscontrol.log
     * */
   /* public static void main(String[] args){


       /*String s = sendPostByJson("http://10.0.0.220:80/ISAPI/AccessControl/UserInfo/Search?format=json", "{\n" +
                "    \"UserInfoSearchCond\":{\n" +
                "        \"searchID\":\"20200706 19:17:03\",\n" +
                "        \"searchResultPosition\":0,\n" +
                "        \"maxResults\":30\n" +
                "    }\n" +
                "}", 0,"admin","a1234567");
        JSONObject jo = JSONObject.parseObject(s);
        System.out.println(jo);*/



     /*   String s1 = httpPutRaw("http://10.0.0.220:80/ISAPI/AccessControl/UserInfo/Delete?format=json", "{\n" +
                "    \"UserInfoDelCond\" : {\n" +
                "        \"EmployeeNoList\" : [  \n" +
                "            {\n" +
                "                \"employeeNo\": \"1241321\"   \n" +
                "            }\n" +
                "        ]\n" +
                "    }\n" +
                "}","admin","a1234567");
        JSONObject jo = JSONObject.parseObject(s1);
        System.out.println(jo.get("statusString"));

        putXml("http://10.220.50.130:80/ISAPI/Image/channels/1/supplementLight", "admin", "a1234567", "on");
    }*/


    static {
        ConnectionKeepAliveStrategy connectionKeepAliveStrategy = new ConnectionKeepAliveStrategy() {
            @Override
            public long getKeepAliveDuration(HttpResponse httpResponse,
                                             HttpContext httpContext) {
                return 20 * 1000; // 20 seconds,because tomcat default keep-alive timeout is 20s
            }
        };
    }



    /**
     * 通过post方式调用http接口
     * @param url     url路径
     * @param jsonParam son格式的参数
     * @param reSend   重发次数
     */
    public static String sendPostByJson(String url, String jsonParam,int reSend,String userName,String passWrod) {
        //声明返回结果
        String result = "";
        //开始请求API接口时间
        long startTime=System.currentTimeMillis();
        //请求API接口的响应时间
        long endTime= 0L;
        HttpEntity httpEntity = null;
        HttpResponse httpResponse = null;
        HttpClient httpClient = null;
        try {
            // 创建连接
            httpClient = HttpClientFactory.getInstance().getHttpClient();
            // 设置请求头和报文
            HttpPost httpPost = HttpClientFactory.getInstance().httpPost(url);
            Header header=new BasicHeader("Accept-Encoding",null);
            httpPost.setHeader(header);
            // 设置报文和通讯格式
            StringEntity stringEntity = new StringEntity(jsonParam, HttpConstant.UTF8_ENCODE);
            stringEntity.setContentEncoding(HttpConstant.UTF8_ENCODE);
            stringEntity.setContentType(HttpConstant.APPLICATION_JSON);
            httpPost.setEntity(stringEntity);
            //log.info("请求{}接口的参数为{}",url,jsonParam);
            //执行发送，获取相应结果
            HttpClient defaultHttpClient = httpClient();
            HttpClient digestHttpClient = digestHttpClient(userName,passWrod,null,null);
            httpResponse = digestHttpClient.execute(httpPost);
            httpEntity= httpResponse.getEntity();
            result = EntityUtils.toString(httpEntity);
        } catch (Exception e) {
            log.error("请求{}接口出现异常",url,e);
            if (reSend > 0) {
                log.info("请求{}出现异常:{}，进行重发。进行第{}次重发",url,e.getMessage(),(HttpConstant.REQ_TIMES-reSend +1));
                result = sendPostByJson(url, jsonParam, reSend - 1,userName,passWrod);
                if (result != null && !"".equals(result)) {
                    return result;
                }
            }
        }finally {
            try {
                EntityUtils.consume(httpEntity);
            } catch (IOException e) {
                log.error("http请求释放资源异常",e);
            }
        }
        //请求接口的响应时间
        endTime=System.currentTimeMillis();
        //log.info("请求{}接口的响应报文内容为{},本次请求API接口的响应时间为:{}毫秒",url,result,(endTime-startTime));
        return result;
    }

    /**
     * @param url 请求地址
     * @param stringJson 参数
     */
    public static String httpPutRaw(String url,String stringJson,String userName, String passWord){
        HttpClient defaultHttpClient = httpClient();
        HttpClient digestHttpClient = digestHttpClient(userName,passWord,null,null);
        HttpPut httpput = new HttpPut(url);
        //设置header
        httpput.setHeader("Content-type", "application/json");
        //组织请求参数
        StringEntity stringEntity = new StringEntity(stringJson,  HttpConstant.UTF8_ENCODE);
        httpput.setEntity(stringEntity);
        //log.info("请求{}接口的参数为{}",url,stringJson);
        String content = null;
        try {

            HttpResponse response = digestHttpClient.execute(httpput);
            HttpEntity entity = response.getEntity();
            content = EntityUtils.toString(entity,  HttpConstant.UTF8_ENCODE);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return content;
    }

    /***
     *  put xml
     * @param userName
     * @param passWrod
     * @param flag
     * @return
     */

    public static String putXml(String url, String userName, String passWrod, String flag) {
        HttpResponse httpResponse = null;
        HttpEntity httpEntity = null;
        try {
            URI uri = new URI(url);
            HttpPut httpPut = new HttpPut(uri);
            httpPut.setHeader("Content-Type", "text/xml");
            httpPut.addHeader("User-Agent", "okhttp/3.6.0");
            String requestBody = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><SupplementLight version=\"2.0\" xmlns=\"http://www.isapi.org/ver20/XMLSchema\"><mode>"+flag+"</mode><brightnessLimit>88</brightnessLimit></SupplementLight>";
            StringEntity reqEntity = new StringEntity(requestBody, Consts.UTF_8);
            reqEntity.setContentType(JSON_CONTENT_TYPE);
            httpPut.setEntity(reqEntity);
            HttpClient digestHttpClient = digestHttpClient(userName,passWrod,null,null);
            httpResponse = digestHttpClient.execute(httpPut);
            httpEntity= httpResponse.getEntity();
            String result = EntityUtils.toString(httpEntity);
            //log.info("result:{};",result);
            return result;
        } catch (Exception e) {
            //e.printStackTrace();
            //log.error("灯光控制异常",e.getMessage());
        }
        return "";
    }

    /***
     *  put xml 设备矫正时间
     * @param userName
     * @param passWrod
     * @param Date 2020-09-08 15:10:10
     * @return
     */
    public static String putXmlDate(String url, String userName, String passWrod, String Date) {
        HttpResponse httpResponse = null;
        HttpEntity httpEntity = null;
        try {
            URI uri = new URI(url);
            HttpPut httpPut = new HttpPut(uri);
            httpPut.setHeader("Content-Type", "text/xml");
            httpPut.addHeader("User-Agent", "okhttp/3.6.0");
            String requestBody = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Time><timeMode>manual</timeMode><localTime>"+Date.replace(" ","T")+"</localTime><timeZone>CST-8:00:00</timeZone></Time>";
            StringEntity reqEntity = new StringEntity(requestBody, Consts.UTF_8);
            reqEntity.setContentType(JSON_CONTENT_TYPE);
            httpPut.setEntity(reqEntity);
            HttpClient digestHttpClient = digestHttpClient(userName,passWrod,null,null);
            httpResponse = digestHttpClient.execute(httpPut);
            httpEntity= httpResponse.getEntity();
            String result = EntityUtils.toString(httpEntity);
            return result;
        } catch (Exception e) {
            //e.printStackTrace();
            //log.error("矫正时间异常：{}",e.getMessage());
        }
        return "";
    }

    /***
     *  put xml 设备信息配置
     * @return
     * <HostInfo>http://10.220.46.136:8089</HostInfo>     //心跳服务器地址
     * <HeartBeat>30</HeartBeat>	//心跳间隔 s
     * <Eyedis>5</Eyedis>			//照片质量眼间距
     * <Yaw>20</Yaw>				//照片质量左右角度
     * <Roll>15</Roll>				//照片质量水平角度
     * <Pitch>10</Pitch>			//照片质量上下角度
     */
    public static String dvrInfoSet(String url, String userName, String passWrod,String HostInfo, String HeartBeat, String Eyedis, String Yaw, String Roll, String Pitch) {
        HttpResponse httpResponse = null;
        HttpEntity httpEntity = null;
        try {
            URI uri = new URI(url);
            HttpPut httpPut = new HttpPut(uri);
            httpPut.setHeader("Content-Type", "text/xml");
            httpPut.addHeader("User-Agent", "okhttp/3.6.0");
            String requestBody = "<CustomCfg version=\"2.0\" xmlns=\"http://www.isapi.org/ver20/XMLSchema\">\n" +
                    "<HostInfo>"+HostInfo+"</HostInfo>\n" +
                    "<HeartBeat>"+HeartBeat+"</HeartBeat>\n" +
                    "<Eyedis>"+Eyedis+"</Eyedis>\n" +
                    "<Yaw>"+Yaw+"</Yaw>\n" +
                    "<Roll>"+Roll+"</Roll>\n" +
                    "<Pitch>"+Pitch+"</Pitch>\n" +
                    "</CustomCfg>";
            StringEntity reqEntity = new StringEntity(requestBody, Consts.UTF_8);
            reqEntity.setContentType(JSON_CONTENT_TYPE);
            httpPut.setEntity(reqEntity);
            HttpClient digestHttpClient = digestHttpClient(userName,passWrod,null,null);
            httpResponse = digestHttpClient.execute(httpPut);
            httpEntity= httpResponse.getEntity();
            String result = EntityUtils.toString(httpEntity);
            return result;
        } catch (Exception e) {
            //e.printStackTrace();
            log.error("设备信息配置异常：{}",e.getMessage());
        }
        return "";
    }












    private static final String JSON_CONTENT_TYPE = "utf-8";

    /***
     *  post xml 下发广告图片，目前只下发图片，后续在做视频下发 1第一步执行完毕后，马上执行post请求，即可下发图片
     * @params url 下发设备ip
     * @param userName 设备名称
     * @param passWrod 设备密码
     * @param fileName 5eb4d75agw1e28ypznbazj
     * @param fileSize 32557
     * @return
     */
    public static String postXmlImg(String ip, String userName, String passWrod, String fileName, long fileSize, File file) {
        HttpResponse httpResponse = null;
        HttpEntity httpEntity = null;
        try {
            if(StringUtils.isEmpty(ip)){
                return "设备ip不能为空";
            }
            String time = DateUtils.getTime();
            String url = "http://"+ip+"/ISAPI/Publish/MaterialMgr/material";
            URI uri = new URI(url);
            HttpPost httpPost = new HttpPost(uri);
            httpPost.setHeader("Content-Type", "text/xml");
            httpPost.addHeader("User-Agent", "okhttp/3.6.0");
            String requestBody = "<Material><id>0</id><materialName>"+fileName+"</materialName><materialRemarks></materialRemarks><materialType>static</materialType><approveState>notApprove</approveState><approveRemarks></approveRemarks><shareProperty>private</shareProperty><uploadUser></uploadUser><uploadTime>"+time+"</uploadTime><orgNo>undefined</orgNo><replaceTerminal></replaceTerminal><StaticMaterial><staticMaterialType>picture</staticMaterialType><picFormat>jpg</picFormat><fileSize>"+fileSize+"</fileSize></StaticMaterial></Material>";
            StringEntity reqEntity = new StringEntity(requestBody, Consts.UTF_8);
            reqEntity.setContentType(JSON_CONTENT_TYPE);
            httpPost.setEntity(reqEntity);
            HttpClient digestHttpClient = digestHttpClient(userName,passWrod,null,null);
            httpResponse = digestHttpClient.execute(httpPost);
            httpEntity= httpResponse.getEntity();
            String result = EntityUtils.toString(httpEntity);
            if(result.contains("OK")){
                Thread.sleep(1000);
                //开始调用put接口下发图片
                String putUrl = "http://"+ip+"/ISAPI/Publish/MaterialMgr/material/1/upload";
                Map<String, String> params = new HashMap<String, String>();
                params.put("id","WU_FILE_1");
                params.put("type","image/jpeg");
                params.put("lastModifiedDate",time);
                params.put("size",String.valueOf(fileSize));
                //String s = uploadFile(ip, file, userName, passWrod, params,null);
                //System.out.println(s);
                //test();
            }
            return result;
        } catch (Exception e) {
            //e.printStackTrace();
            log.error("下发图片异常：{}",e);
        }
        return "";
    }



    public static HttpClient digestHttpClient(String username, String password,String host,Integer port){
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(new AuthScope(StringUtils.isBlank(host) ? AuthScope.ANY_HOST : host, port == null ? AuthScope.ANY_PORT : port),
                new UsernamePasswordCredentials(username,password));
        // 创建默认的httpClient实例.
        RequestConfig defaultRequestConfig = RequestConfig.custom()
                .setSocketTimeout(20000)
                .setConnectTimeout(20000)
                .setConnectionRequestTimeout(20000)
                .setStaleConnectionCheckEnabled(true)
                .build();
        return HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).setDefaultRequestConfig(defaultRequestConfig).build();
    }

    public static HttpClient httpClient(){
        return HttpClients.custom().build();
    }

}
